package org.lzy.shop.util

import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import org.lzy.shop.R
import java.util.concurrent.atomic.AtomicBoolean

/**
 * BannerManager类用于管理ViewPager2实现的轮播图
 * 使用协程代替Handler实现自动轮播
 */
class BannerManager<T>(
    private val viewPager2: ViewPager2,
    private val indicatorsContainer: LinearLayout,
    private val lifecycleOwner: LifecycleOwner,
    dataList: List<T>,
    private val autoScrollDelay: Long = 5000,
    private val isInfiniteLoop: Boolean = true
) : DefaultLifecycleObserver {

    private var adapter: BannerAdapter? = null
    private var currentPage = 0
    private var isUserScrolling = false
    private var isAutoScrollRunning = AtomicBoolean(false)
    private val scope = lifecycleOwner.lifecycleScope
    private var autoScrollJob: Job? = null
    // 将dataList改为可变列表
    private val dataList: MutableList<T> = mutableListOf()

    // 图片加载器接口
    private var imageLoader: ((imageView: ImageView, item: T) -> Unit)? = null
    // 点击事件接口
    private var onItemClickListener: ((position: Int, item: T) -> Unit)? = null

    init {
        // 初始化数据列表
        this.dataList.addAll(dataList)
    }

    // 设置新数据并刷新轮播图
    fun setData(newData: List<T>) {
        val oldDataSize = dataList.size

        // 更新内部数据列表
        dataList.clear()
        dataList.addAll(newData)

        // 重新初始化指示器
        initIndicators()

        // 如果是无限滚动且数据发生变化，重新设置初始位置
        if (isInfiniteLoop && dataList.size > 1 && oldDataSize != dataList.size) {
            val middlePosition = Int.MAX_VALUE / 2
            val offset = middlePosition % dataList.size
            viewPager2.setCurrentItem(middlePosition - offset, false)
            currentPage = middlePosition - offset
        }

        // 通知适配器数据变化
        adapter?.notifyDataSetChanged()

        // 重置自动轮播
        resetAutoScroll()
    }

    // 初始化方法
    fun initialize() {
        // 注册生命周期监听
        lifecycleOwner.lifecycle.addObserver(this)

        // 设置适配器
        adapter = BannerAdapter()
        viewPager2.adapter = adapter

        // 设置ViewPager2配置
        setupViewPager2()

        // 初始化指示器
        initIndicators()

        // 如果是无限滚动，设置初始位置
        if (isInfiniteLoop && dataList.size > 1) {
            val middlePosition = Int.MAX_VALUE / 2
            val offset = middlePosition % dataList.size
            viewPager2.setCurrentItem(middlePosition - offset, false)
            currentPage = middlePosition - offset
        }

        // 开始自动轮播
        startAutoScroll()
    }

    // 设置图片加载器
    fun setImageLoader(loader: (imageView: ImageView, item: T) -> Unit) {
        this.imageLoader = loader
    }

    // 设置点击事件
    fun setOnItemClickListener(listener: (position: Int, item: T) -> Unit) {
        this.onItemClickListener = listener
    }

    // 设置ViewPager2配置
    private fun setupViewPager2() {
        // 启用页面缓存
        viewPager2.offscreenPageLimit = 1

        // 设置滚动监听器
        viewPager2.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                currentPage = position

                // 更新指示器
                updateIndicators(position)

                // 如果用户手动滑动，重置自动轮播
                if (isUserScrolling && isAutoScrollRunning.get()) {
                    resetAutoScroll()
                }
            }

            override fun onPageScrollStateChanged(state: Int) {
                super.onPageScrollStateChanged(state)

                when (state) {
                    ViewPager2.SCROLL_STATE_DRAGGING -> {
                        // 用户开始滑动
                        isUserScrolling = true
                        pauseAutoScroll()
                    }
                    ViewPager2.SCROLL_STATE_IDLE -> {
                        // 滚动停止
                        isUserScrolling = false
                        startAutoScroll()
                    }
                }
            }
        })

        // 设置触摸事件监听器
        viewPager2.setOnTouchListener {
                _, event ->
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    pauseAutoScroll()
                }
                MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                    if (!isUserScrolling) {
                        startAutoScroll()
                    }
                }
            }
            false
        }
    }

    // 初始化指示器
    private fun initIndicators() {
        indicatorsContainer.removeAllViews()

        val context = indicatorsContainer.context
        val indicatorSize = 8 // dp
        val indicatorMargin = 4 // dp
        val pixelSize = (indicatorSize * context.resources.displayMetrics.density).toInt()
        val pixelMargin = (indicatorMargin * context.resources.displayMetrics.density).toInt()

        for (i in 0 until dataList.size) {
            val indicator = ImageView(context)
            val params = LinearLayout.LayoutParams(pixelSize, pixelSize)
            params.setMargins(pixelMargin, 0, pixelMargin, 0)
            indicator.layoutParams = params

            // 设置指示器样式
            indicator.setImageResource(
                if (i == 0) R.drawable.banner_indicator_dot_selected
                else R.drawable.banner_indicator_dot_normal
            )

            indicatorsContainer.addView(indicator)
        }
    }

    // 更新指示器
    private fun updateIndicators(position: Int) {
        if (dataList.isEmpty()) return

        val actualPosition = getActualPosition(position)

        for (i in 0 until indicatorsContainer.childCount) {
            val indicator = indicatorsContainer.getChildAt(i) as ImageView
            indicator.setImageResource(
                if (i == actualPosition) R.drawable.banner_indicator_dot_selected
                else R.drawable.banner_indicator_dot_normal
            )
        }
    }

    // 获取实际位置
    private fun getActualPosition(position: Int): Int {
        return if (dataList.isEmpty()) 0 else position % dataList.size
    }

    // 开始自动轮播
    private fun startAutoScroll() {
        if (dataList.size <= 1 || !isAutoScrollRunning.compareAndSet(false, true)) {
            return
        }

        autoScrollJob = scope.launch(Dispatchers.Main) {
            try {
                while (isActive) {
                    delay(autoScrollDelay)
                    if (!isUserScrolling) {
                        // 滚动到下一页
                        viewPager2.setCurrentItem(currentPage + 1, true)
                    }
                }
            } catch (e: CancellationException) {
                // 协程被取消，正常现象
            } finally {
                isAutoScrollRunning.set(false)
            }
        }
    }

    // 暂停自动轮播
    private fun pauseAutoScroll() {
        autoScrollJob?.cancel()
        isAutoScrollRunning.set(false)
    }

    // 重置自动轮播
    private fun resetAutoScroll() {
        pauseAutoScroll()
        // 延迟启动自动轮播，避免短时间内频繁切换
        scope.launch(Dispatchers.Main) {
            delay(1000) // 1秒延迟
            startAutoScroll()
        }
    }

    // 生命周期事件 - 暂停时停止轮播
    override fun onPause(owner: LifecycleOwner) {
        pauseAutoScroll()
    }

    // 生命周期事件 - 恢复时开始轮播
    override fun onResume(owner: LifecycleOwner) {
        if (!isUserScrolling) {
            startAutoScroll()
        }
    }

    // 生命周期事件 - 销毁时清理资源
    override fun onDestroy(owner: LifecycleOwner) {
        pauseAutoScroll()
        viewPager2.adapter = null
        // 清空数据列表，释放引用
        dataList.clear()
        // 清除ViewPager2的适配器和监听器
        viewPager2.adapter = null
        viewPager2.setOnTouchListener(null)
        // 清空指示器容器
        indicatorsContainer.removeAllViews()
        // 移除生命周期观察者，防止内存泄漏
        owner.lifecycle.removeObserver(this)
        // 清空回调引用，避免潜在的内存泄漏
        imageLoader = null
        onItemClickListener = null
    }

    // Banner适配器
    inner class BannerAdapter : RecyclerView.Adapter<BannerAdapter.BannerViewHolder>() {

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BannerViewHolder {
            val itemView = LayoutInflater.from(parent.context)
                .inflate(R.layout.item_banner, parent, false)
            return BannerViewHolder(itemView)
        }

        override fun onBindViewHolder(holder: BannerViewHolder, position: Int) {
            val actualPosition = getActualPosition(position)
            val item = dataList[actualPosition]

            // 加载图片
            imageLoader?.invoke(holder.imageView, item)

            // 设置点击事件
            holder.itemView.setOnClickListener {
                onItemClickListener?.invoke(actualPosition, item)
            }
        }

        override fun getItemCount(): Int {
            return if (isInfiniteLoop && dataList.size > 1) Int.MAX_VALUE else dataList.size
        }

        inner class BannerViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            val imageView: ImageView = itemView.findViewById(R.id.bannerImage)
        }
    }
}